<?php
class ModuleInstaller extends CApplicationComponent
{
	private $_file;
	private $_tempPath; 
	private $_modulePath;
	private $_moduleName; 
	
	const INSTALL_XML = 'install.xml';
	
	public function install($file)
	{
		$this->_file = $file;
		$this->_tempPath = Yii::app()->basePath . '/../images/';
		$this->_modulePath = Yii::app()->basePath . '/modules/';
		
		$this->_file->saveAs($this->_tempPath.$this->_file);
		$this->_unzip($this->_tempPath, $this->_tempPath);
		if($this->_saveModule())
		{
			$this->_unzip($this->_tempPath, $this->_modulePath);
			$this->_deleteTempFiles();			
		}else{
			echo 'XML Incorrect attributes';
		}
	}
	
	private function _unzip($src, $dest)
	{
		$zip = new ZipArchive;
	    $res = $zip->open($src. $this->_file);
	    if ($res) 
	    {
	        $zip->extractTo($dest);
	        $zip->close();	       
	    } 
	}	
	
	private function _saveModule()
	{		
		$xml = simplexml_load_file($this->_tempPath . self::INSTALL_XML ); 
		$model = Module::model()->findByAttributes(array('name' => $xml->meta['name']));
		if(!$model)	
			$model = new Module;

		$this->_moduleName = $model->name = $xml->meta['name'];	
		$model->description = $xml->meta['description'];
		$model->version = $xml->meta['version'];
		return $model->save();
	}
	
	private function _deleteTempFiles()
	{
		unlink($this->_tempPath. $this->_file);
		unlink($this->_tempPath. self::INSTALL_XML);
		$this->deleteDir($this->_tempPath.$this->_moduleName);
		unlink($this->_modulePath. self::INSTALL_XML);		
	}
	
	public function deleteDir($dir) 
	{
	   if (is_dir($dir)) {
	     $objects = scandir($dir);
	     foreach ($objects as $object) {
	       if ($object != "." && $object != "..") {
	         if (filetype($dir."/".$object) == "dir") $this->deleteDir($dir."/".$object); else unlink($dir."/".$object);
	       }
	     }
	     reset($objects);
	     rmdir($dir);
	   }
	 }
}
?>